package jetpack.com.pzl.works;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.ListenableWorker;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

public class LoadNetTextWorker extends Worker {
    final String TAG = "jinx_LoadNetTextWorker";

    public LoadNetTextWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }


    @NonNull
    @Override
    public ListenableWorker.Result doWork() {
        Log.i(TAG, "doWork ---");
        String message = "";
        try {
            String urlParam = getInputData().getString("url");
            URL url = new URL(urlParam);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5 * 1000);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            byte[] data = new byte[1024];
            StringBuffer sb = new StringBuffer();
            int length = 0;
            while ((length = inputStream.read(data)) != -1) {
                String s = new String(data, Charset.forName("utf-8"));
                sb.append(s);
            }
            message = sb.toString();
            inputStream.close();
            connection.disconnect();
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
            e.printStackTrace();
        }
        Log.i(TAG, message);
        //放入数据结果  返回
        Data.Builder builder = new Data.Builder();
        builder.putString("result", message);
        return Result.success(builder.build());
    }


}
